#include <string.h>
#include<stdio.h>
#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    mysocket = new QTcpSocket;  // new 对象
    mysocket->connectToHost("192.168.1.8",6666);

    connect(mysocket,SIGNAL(connected()),this,SLOT(my_connect()));
    connect(mysocket,SIGNAL(disconnected()),this,SLOT(my_disconnect()));

    connect(mysocket,SIGNAL(readyRead()),this,SLOT(myrecv()));

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::my_connect()
{

}

void MainWindow::my_disconnect()
{
    ui->label_connect->setText("断开连接");
    ui->label_name->setText(" ");
}

void MainWindow::myrecv()
{
    char buf[1024]={0};
    mysocket->read(buf,sizeof(buf));

    //判断消息类型
    char *pos=strchr(buf,' ');
    if(buf[0]=='1')   //收发消息
    {
        ui->textBrowser->insertPlainText(pos);
        ui->textBrowser->moveCursor(QTextCursor::End);
    }
    else if(buf[0]=='0')  //定义用户
    {
        ui->label_name->setText(pos);
        ui->label_connect->setText("已连接");
        mysocket->read(buf,sizeof(buf));
        char *pos=strchr(buf,' ');
        ui->textBrowser->insertPlainText(pos);
        ui->textBrowser->moveCursor(QTextCursor::End);
    }


}

void MainWindow::on_pushButton_clicked()
{
    //获取字符串
    QString text = ui->textEdit->toPlainText();
    std::string s=text.toStdString();
    char *out=(char *)s.c_str();
    if(text.length()>=1024) out[1001]='\0';

    //发送信息
    mysocket->write(out);

    //清空输入框
    ui->textEdit->clear();
    ui->textEdit->setFocus();
}


void MainWindow::on_pushButton_connect_clicked()
{
    mysocket->connectToHost("192.168.1.8",6666);
}

